<?php

class Newsfeed extends Controller {
	function Newsfeed() {
		parent::Controller();
		$this->is_logged_in();
	}
	
	function edit($newsfeed_id = "-1") {
		$data['menu'] = array('nf_select', 'nf_create', 'logout');
		$data['content'] = array('editing/edit');
		$data['newsfeed_id'] = $newsfeed_id;
		$data['newsfeed_title'] = $this->newsfeed_model->get_newsfeed_property($newsfeed_id, 'title');
		$data['newsfeed_who'] = $this->newsfeed_model->get_newsfeed_property($newsfeed_id, 'who');
		$this->load->view('editing/edit', $data);
	}
	
	
	function select($flash = "") {
		// retrieve all newsfeeds owned by the user
		
		$data['menu'] = array('nf_select', 'nf_create', 'logout');
		if ($flash != "") {
			$data['content'] = array($flash, 'newsfeed/select');
		} else {
			$data['content'] = array('newsfeed/select');
		}
		$data['newsfeeds'] = $this->newsfeed_model->get_newsfeeds();
		$this->load->view('includes/template', $data);
		
	}
	
	function delete($newsfeed_id = "-1") {
		$data['menu'] = array('nf_select', 'nf_create', 'logout');
		
		// check this user is owner of the newsfeed
		if ($this->newsfeed_model->check_newsfeed_ownership($newsfeed_id)) {
			// they own the newsfeed
			if ($this->newsfeed_model->delete_newsfeed($newsfeed_id)) {
				$this->select('newsfeed/flash_deleted');
			} else {
				$this->select('newsfeed/flash_delete_fail');
			}
		} else {
			// they don't own the newsfeed
			$this->select('newsfeed/flash_no_permission');
		}
	}
	
	function create_newsfeed() {
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('title', 'Title', 'trim|required');
		$this->form_validation->set_rules('who', 'Who', 'trim|required');
		
		if ($this->form_validation->run() == FALSE) {
			$this->create();
		} else {
			if ($query = $this->newsfeed_model->create_newsfeed()) {
				// newsfeed created successfully
				$data['menu'] = array('nf_select', 'nf_create', 'logout');
				$data['content'] = array('newsfeed/flash_created', 'newsfeed/select');
				$data['newsfeeds'] = $this->newsfeed_model->get_newsfeeds();
				$this->load->view('includes/template', $data);
			} else {
				$this->load->view('newsfeed/create');
			}
		}
	}
	
	function create() {
		$data['menu'] = array('nf_select', 'nf_create', 'logout');
		$data['content'] = array('newsfeed/create_newsfeed');
		$this->load->view('includes/template', $data);
	}
	
	
	function is_logged_in() {
		$is_logged_in = $this->session->userdata('is_logged_in');
		
		if (!isset($is_logged_in) || $is_logged_in != TRUE) {
			redirect('auth/index', 'refresh');
		}
	}
}
